from random import random

from domain import Proxy
from pymongo import MongoClient
from settings import MONGO_URL
from utils.log import logger


class MongoPool(object):
    def __init__(self):
        self.client = MongoClient(MONGO_URL)
        self.proxies = self.client['proxies_pool']['proxies']

    def __del__(self):
        self.client.close()

    def insert_one(self,proxy):

        count = self.proxies.count({'_id':proxy.ip})
        if count == 0:
            dic = proxy.__dict__
            dic['id'] = proxy.ip
            self.proxies.insert_one(dic)
            logger.info('插入新的代理：{}'.format(proxy))
        else:
            logger.warning("代理已经存在：{}".format(proxy))

    def undate_one(self,proxy):
        self.proxies.update_one({'_id':proxy.ip},{'$set':proxy.__dict__})

    def delete_one(self, proxy):
        self.proxies.delete_one({'_id':proxy.ip})
        logger.info("删除代理IP：{}".format(proxy))

    def find_all(self):
        cusor = self.proxies.find()
        for item in cusor:
            item.pop('_id')
            proxy = Proxy(**item)
            yield proxy

    def find(self,condtions=(),count=0):
        cursor = self.proxies.find(condtions,limit=count),sort([
            ('score',pymongo.DESCENDING),('speed',pymongo.ASCENDING)
        ])

        proxy_list = []
        for item in cursor:
            item.pop('_id')
            proxy = Proxy(**item)
            proxy_list.append(proxy)
        return proxy_list

    def get_proxies(self,protocol=None,domain=None,count=0,nick_type=0):
        conditions = {'nick_type':nick_type}
        if protocol in None:
            conditions['protocol'] = 2
        elif protocol.lower() == 'hppt':
            conditions['protocol'] = {'$in':[0,2]}
        else:
            conditions['protocol'] = {'$in':[1,2]}
        if domain:
            conditions['disadle_domains'] = {'$nin':[domain]}
        return self.find(conditions,count=count)

    def random_proxy(self,protocol=None,domain=None,count=0,nick_type=0):
        proxy_list = self.get_proxies(protocol=protocol,domain=domain,count=count,nick_type=nick_type)
        return random.choice(proxy_list)

    def disable_domain(self,ip,domain):
        if self.proxies.count_documents({'_id':ip,'disable_domains':domain}):
            self.proxies.update_one({'_id':ip},{'$push':{'disable_domains': domain}})
            return True
        return False


if __name__ == '__main__':
    mongo = MongoPool()

    proxy = Proxy('202.104.113.35', port='53201')
    mongo.insert_one(proxy)
    proxy = Proxy('202.104.113.35', port='53201')
    mongo.delete_one(proxy)
    # for proxy in mongo.find_all():
    #     print(proxy)

    # mongo = MongoPool(proxy)
#     09看完
